package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.ArgsUtil
import com.yige.common.ExcelFileGenerator
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.common.ToDBObjectUtil
import com.yige.service.mongoService.MongoResourceService
import com.yige.service.mongoService.MongoRoleService
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.ModelMap
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.View
import org.springframework.web.servlet.view.document.AbstractExcelView

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * Created by sunhao on 2015/9/17 0017.
 */
@Controller
@RequestMapping("resource")
class ResourceController {


    @Autowired
    MongoResourceService resourceService
    @Autowired
    MongoRoleService roleService



    /*************控制器模块************/

    /**
     * 显示资源管理页面
     * @param model
     * @return
     */
    @RequestMapping("/list.do")
    def list(Model model){
        List<DBObject> resourceList = resourceService.findList()
        model.addAttribute("resources",resourceList)
        groupArgs(model,resourceList)
        return "resource/list"
    }

    /**
     * 多条件查询资源
     * @param model
     * @param name
     * @param url
     * @param type
     * @param available
     * @return
     */
    @RequestMapping("/find")
    def find(Model model,String name,String url,String type,Integer available,Integer group){
        def query = new BasicDBObject()
        //判断query条件
        if(!StringUtils.isEmpty(name)){
            query.append("name",~/${name}/)
        }
        if(!StringUtils.isEmpty(url)){
            query.append("url",~/${url}/)
        }
        if(!StringUtils.isEmpty(type)){
            query.append("type",~/${type}/)
        }
        if(available == null){
            query.append("available",[$in:[1,0]]as BasicDBObject)
        } else if(available != -1){
            query.append("available",available)
        }
        if(group == null){
            int max = resourceByGroup()
            int[] vec = new int[max]
            for(int i=0;i<max;i++){
                vec[i]=i+1;
            }
            query.append("group",[$in:vec]as BasicDBObject)
        }else{
            query.append("group",group)
        }
        List<DBObject> resources = resourceService.findListByQuery(query)
        model.addAttribute("resources",resources)
        groupArgs(model,resources)
        return "resource/list"
    }

    /**
     * 添加资源
     * @param name
     * @param description
     * @return
     */
    @RequestMapping("addResource")
    @ResponseBody
    def addResource(String name,String type, String url, Integer available,Integer group){
        //创建资源信息
        if(group == 0 || group == null){
            //自动创建新组
            group = ++resourceByGroup()
        }
        Map<String,Object> resourceInfo = [
                _id:UUID.randomUUID().toString(),
                name:name,
                type:type,
                url:url,
                available:available,
                group:group
        ]
        DBObject dbObject = ToDBObjectUtil.toDBObject(resourceInfo)
        boolean flag = saveResource(dbObject)
        if(flag){//增加超级管理员相应权限
            def adminId = SystemConstant.ADMINISTRATTOR_ID as String
            roleService.bindResourceForRole(adminId,dbObject._id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 修改资源
     * @param _id
     * @param name
     * @param description
     * @return
     */
    @RequestMapping("updateResource")
    @ResponseBody
    def updateResource(String _id,String name,String type, String url,Integer available, Integer group){
        //创建资源信息
        Map<String,Object> resourceInfo = [_id:_id,name:name,type:type,url:url,available:available,group:group ]
        DBObject dbObject = ToDBObjectUtil.toDBObject(resourceInfo)
        boolean flag = updateResource(dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 删除资源
     * @param _ids
     * @return
     */
    @RequestMapping("delResource")
    @ResponseBody
    def delResource(@RequestParam("_ids") List<String> _ids){
        //遍历删除资源
        boolean flag = false
        _ids.each {_id->
            flag = resourceService.deleteOne(_id)
            if(flag){//删除超级管理员对应的权限
                def adminId = SystemConstant.ADMINISTRATTOR_ID as String
                roleService.removeResourceForRole(adminId,_id)
            }
        }
        ResultUtil.recallAjax(flag)
    }


    /**
     * 导出资源表格
     * @param modelMap
     * @return
     */
    @RequestMapping("export.do")
    def export(ModelMap modelMap){
        View view = new AbstractExcelView() {

            @Override
            protected void buildExcelDocument(Map map,
                                              HSSFWorkbook workbook, HttpServletRequest request,
                                              HttpServletResponse response) throws Exception {
                //定义Excel表参数
                String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls";
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + filename) ;

                // 建立 Sheet
                List<String> fieldName = new ArrayList<>()
                fieldName.add("ID")
                fieldName.add("资源名称")
                fieldName.add("资源类型")
                fieldName.add("url")
                fieldName.add("分组ID")
                List<List<Object>> fieldData = new ArrayList<>()
                List<DBObject> resourceList = resourceService.findList()
                resourceList.each {info->
                    fieldData.add([info._id, info.name, info.type, info.url,info.group]as ArrayList)
                }
                ExcelFileGenerator excel = new ExcelFileGenerator(fieldName,fieldData)
                //开启输出流
                OutputStream ouputStream = response.getOutputStream();
                //输出Excel表
                excel.exportExcel(ouputStream)
            }
        }
        return new ModelAndView(view,modelMap)
    }



    /*************方法模块***************/

    def saveResource(DBObject resource){
        ArgsUtil.checkArgs(resource)
        //判断资源是否存在
        DBObject resource_db = resourceService.findOneById(resource._id)
        if (resource_db == null) {
            if (resource.get("available") == null) {
                resource.put("available", SystemConstant.RESOURCE_ON_JOB)
            }
            resourceService.insertOne(resource)
            return true
        }else{
            return false
        }

    }

    def updateResource(DBObject resource) {
        ArgsUtil.checkArgs(resource)
        resourceService.updateOne(resource._id,resource)
        return true
    }

    def resourceByGroup(){
        List<DBObject> resourceList = resourceService.findList(),
                       countList = new ArrayList<>()
        resourceList.each {info->
            if(SystemConstant.RESOURCE_TYPE_NAV.equals(info.type)){
                countList.add(info)
            }
        }
        int count = countList.size()
        return count
    }

    def groupArgs(Model model ,List<DBObject> resourceList){
        Set<Integer> groupSet = new LinkedHashSet<>()
        resourceList.each {info->
            groupSet.add(info.group)
        }
        def group = new ArrayList(groupSet)
        model.addAttribute("group",group)
    }

}
